package com.ourhealth.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ourhealth.mapper.PermissionMapper;
import com.ourhealth.mapper.RoleMapper;
import com.ourhealth.mapper.UserMapper;
import com.ourhealth.pojo.Permission;
import com.ourhealth.pojo.Role;
import com.ourhealth.pojo.User;
import com.ourhealth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author dddddh
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public User findUserByUsername(String username) {
//        User user = userMapper.findUserByUsername(username);
//        if (user!=null){
//            Integer userId = user.getId();
//            Set<Role> roles = roleMapper.findRolesByUserId(userId);
//            if (roles!=null){
//                for (Role role : roles) {
//                    Integer roleId = role.getId();
//                    Set<Permission> permissions = permissionMapper.findPermissionByRoleId(roleId);
//                    if (permissions!=null&&permissions.size()>0){
//                    role.setPermissions(permissions);
//                    }
//                }
//                user.setRoles(roles);
//            }
//            return user;
//        }
        User user = userMapper.findUserByUsername(username);
        if (user!=null){
            Set<Role> rolesByUserIds = roleMapper.findRolesByUserId(user.getId());
            if (rolesByUserIds!=null&&rolesByUserIds.size()>0){

                //将所有角色id存入数组
                List<Integer> ids = new ArrayList<>();
                for (Role rolesByUserId : rolesByUserIds) {
                    ids.add(rolesByUserId.getId());
                }
                //获取所有与角色有关系的权限
                List<Permission> permissions = permissionMapper.findPermission(ids);

                Map<Integer,Set<Permission>> map = new HashMap<>();
                for (Permission permission : permissions) {
                    Set<Permission> permissions1 = map.get(permission.getRoleId());
                    if (permissions1==null){
                        permissions1 = new HashSet<>();
                        map.put(permission.getRoleId(),permissions1);
                    }
                    permissions1.add(permission);
                }

                for (Role rolesByUserId : rolesByUserIds) {
                    rolesByUserId.setPermissions(map.get(rolesByUserId.getId()));
                }
                user.setRoles(rolesByUserIds);
            }
            return user;
        }
        return null;
    }
}
